package com.zhangfb95.crosschain.infra.util.json;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zhangfb95.crosschain.infra.exception.BusinessException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * json工具类
 *
 * @author zhangfubing
 * @since 2021/4/15
 */
@Component
public class JsonUtil {

    @Autowired
    private ObjectMapper objectMapper;

    public String toJsonQuietly(Object obj) {
        try {
            return objectMapper.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            throw new BusinessException(e);
        }
    }
    public String toPrettyJsonQuietly(Object obj) {
        try {
            return objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            throw new BusinessException(e);
        }
    }

    public <T> T readValue(String data, TypeReference<T> typeReference) {
        try {
            return objectMapper.readerFor(typeReference).readValue(data);
        } catch (JsonProcessingException e) {
            throw new BusinessException(e);
        }
    }

    public <T> T readValue(String data, Class<T> clazz) {
        try {
            return objectMapper.readerFor(clazz).readValue(data);
        } catch (JsonProcessingException e) {
            throw new BusinessException(e);
        }
    }
}
